from docx import Document
from datetime import datetime


def calculate_age(birth_date, target_date):
    """根据出生日期和目标日期计算年龄"""
    years = target_date.year - birth_date.year
    if (target_date.month, target_date.day) < (birth_date.month, birth_date.day):
        years -= 1
    months = target_date.month - birth_date.month
    if months < 0:
        months += 12
    return years, months


def extract_and_calculate_age(doc_path, table_index=0, col1=1, col2=3):
    # 打开Word文档
    doc = Document(doc_path)

    # 获取指定的表格
    table = doc.tables[table_index]

    results = []
    id_str = 0
    # 跳过前三行，从第四行开始读取
    for i, row in enumerate(table.rows):
        if i < 3:  # 跳过前三行
            continue

        # 第2列的数据
        col2_value = row.cells[col1].text

        # 第4列中的出生日期
        birth_date_str = row.cells[col2].text
        try:
            birth_date = datetime.strptime(birth_date_str, "%Y.%m.%d")
        except ValueError:
            print(f"出生日期格式错误: {birth_date_str}")
            continue

        # 计算到2024年9月的年龄
        target_date_1 = datetime(2024, 9, 1)
        years_1, months_1 = calculate_age(birth_date, target_date_1)
        age_1 = f"{years_1} {months_1}"
        id_str += 1

        # 计算到2024年12月的年龄
        target_date_2 = datetime(2024, 12, 1)
        years_2, months_2 = calculate_age(birth_date, target_date_2)
        age_2 = f"{years_2} {months_2}"

        # 记录第2列与出生日期、年龄的结果
        results.append({
            "id_str": id_str,
            "name": col2_value,
            "birth_date": birth_date_str,
            "age_2024_09": age_1,
            "age_2024_12": age_2
        })

    return results


# 测试读取Word表格中的第2列和第4列，并计算年龄
doc_path = 'C:\\Users\\MI\\Desktop\\1.docx'  # 替换为你的Word文件路径
results = extract_and_calculate_age(doc_path)

# 输出每个孩子的第2列数据、出生日期及年龄
for entry in results:
    print(
        f"{entry['id_str']},{entry['name']},{entry['age_2024_09']},{entry['age_2024_12']}")
